<template>
  <div v-text="quoteHandle()" />
</template>

<script>
import {EventBus, EventType} from "@/event";
import {defineComponent, ref} from "vue";

export default defineComponent({
  name: "IvzSearchForeignItem",
  props: ['meta', 'model'],
  setup(props) {
    const changeEvent = ({val, meta, model}) => {
      if(meta.type == 'foreign') {
        props.model['foreign'] = val;
      } else {
        props.model['quote'] = val;
        props.model['field'] = val[1];
      }

      props.model['title'] = model['title'];
      props.model['target'] = model['target']
    }

    if(props.meta.type == 'foreign') {
      EventBus.listener(EventType.changeForeign, changeEvent);
    } else {
      EventBus.listener(EventType.changeQuote, changeEvent);
    }

    return {changeEvent}
  },
  created() {

  },
  methods: {
    quoteHandle() {
      let quoteValue = this.model['foreign'] || this.model['quote']
      if(this.model.type == 'foreign') {
        return quoteValue ? `一对一 [${this.model.field} -> ${quoteValue.join(":")}]` : `一对一 []`;
      } else if(this.model.type == 'foreignToMany') {
        return quoteValue ? `一对多 [${this.model.field} -> ${quoteValue.join(":")}]` : `一对多 []`;
      } else {
        return quoteValue ? `引用 [${this.model.field} -> ${quoteValue.join(":")}]` : `引用 []`;
      }
    }
  },

  unmounted() {
    // 移除事件
    let events = EventBus.allEvents().get(EventType.changeForeign);
    let findIndex = events.findIndex(cfn => cfn == this.changeEvent);
    if(findIndex > -1) {
      events.slice(findIndex, 1);
    }

    let quoteEvents = EventBus.allEvents().get(EventType.changeQuote);
    let quoteIndex = quoteEvents.findIndex(cfn => cfn == this.changeEvent);
    if(quoteIndex > -1) {
      events.slice(quoteIndex, 1);
    }
  }
})
</script>

<style scoped>

</style>